package joSaysHello.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import joSaysHello.client.GreetingService;
import joSaysHello.shared.entity.Hello;
import joSaysHello.shared.entity.User;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService {
	
	private static final long serialVersionUID = 6979127681187207343L;

	@Override
	public Hello sayHello() {
		PersistenceManager pm = PMFSingleton.getPM();
		User user = UserManager.getCurrentUser(pm);
		if(user == null)
			return null;
		Date now = new Date();
		Hello hello = new Hello(user, now);
		System.out.println(hello.printFull());
		pm.makePersistent(hello);
		pm.close();
		boolean mailed = MailHandler.getInstance().sendMail(user+" said hello!", user+" said hello!", new String[] {"johannes@famfoerstner.de"});
		if(!mailed)
			System.out.println("mailing failed :(");
		return hello;
	}
	
	public List<Hello> getHellos()
	{
		return getHellosSince(null);
	}

	@Override
	public List<Hello> getHellosSince(Date since) {
		PersistenceManager pm = PMFSingleton.getPM();
		Query q = pm.newQuery(Hello.class);
		q.setOrdering("when desc");
		Object result;
		if(since != null)
		{
			q.setFilter("when > sinceParam");
			q.declareImports("import java.util.Date");
			q.declareParameters("Date sinceParam");
			result = q.execute(since);
		}
		else
		{
			result = q.execute();
		}
		@SuppressWarnings("unchecked")
		List<Hello> res = (List<Hello>) result;
		List<Hello> hellos = new ArrayList<Hello>();
		for(Hello hello : res)
		{
			User user = hello.getWho(); // lazy loading before serialization
			System.out.println(user); // even this has to be done so the above loading doesn't get optimized away!
			hellos.add(hello);
		}
		pm.close();
		return hellos;
	}

}
